def prepare_ml_data(df):
df['Future_Close'] = df['close'].shift(-1)
df['Target'] = (df['Future_Close'] > df['close']).astype(int)
features = ['MA20', 'MA50', 'RSI', 'MACD', 'Signal']
df = df.dropna() # 移除 NaN
X = df[features]
y = df['Target']
return X, y
# -------------------------
# Step 4: 訓練 ML 模型
# -------------------------
def train_ml_model(X, y):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, shuffle=False
)
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("混淆矩陣 (Confusion Matrix):")
print(confusion_matrix(y_test, y_pred))
print("\n分類報告 (Classification Report):")
print(classification_report(y_test, y_pred))
return model